//
//  RootViewController.m
//  Device
//
//  Created by  江志磊 on 15-2-3.
//  Copyright (c) 2015年  江 志磊. All rights reserved.
//

#import "RootViewController.h"
//封装了跟系统和硬件相关的一些常量参数
#import <MobileCoreServices/MobileCoreServices.h>
//封装了苹果自带的播放器，底层封装的是AVPlayer
#import <MediaPlayer/MediaPlayer.h>

@interface RootViewController ()
{
    //能够播放绝大多数格式的音频文件
    AVAudioPlayer *_audioPlayer;
    //带有视频播放器的控制器类,自带视频播放器的画面,能够播放mp4、avi、mov以及m3u8流媒体格式的视频;支持播放本地文件和远程地址
    MPMoviePlayerViewController *_playController;
}
@end

@implementation RootViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSArray *titles =@[@"相机",@"相册库",@"音频",@"视频"];
    for (NSInteger i=0; i<titles.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [btn setTitle:titles[i] forState:UIControlStateNormal];
        [btn setFrame:CGRectMake(10,74+i*50,300,40)];
        [btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = i+100;
        [self.view addSubview:btn];
    }
    
    // Do any additional setup after loading the view.
}

- (void)btnClicked:(UIButton *)btn{
    switch (btn.tag) {
        case 100:
        {
            //相机
            //isSourceTypeAvailable 判断资源是否可用
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                [self loadImagePickerWithType:UIImagePickerControllerSourceTypeCamera];
            }else{
                [self showAlertViewWithMessage:@"相机不可用"];
            }
            
        }
            break;
        case 101:
        {
            //相册库
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                [self loadImagePickerWithType:UIImagePickerControllerSourceTypePhotoLibrary];
            }else{
                [self showAlertViewWithMessage:@"无法读取相册库"];
            }
        }
            break;
        case 102:
        {
            //音频
            NSString *path = [[NSBundle mainBundle] pathForResource:@"song1" ofType:@"mp3"];
            [self loadAudioWithPath:path];
        }
            break;
        case 103:
        {
            //视频
            NSString *videoPath = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"mp4"];
            //也可以播音频
            [self loadVideoWithVideoPath:@"http://jiang.local/1.mp4"];
        }
            break;
            
        default:
            break;
    }
    
}

//播放视频
- (void)loadVideoWithVideoPath:(NSString *)videoPath{
    if (videoPath.length==0) {
        NSLog(@"没有视频资源!");
        return;
    }
    NSURL *url;
    // http://   https://(加密的http协议)  认为是远程的播放地址
    //字符串中是否包含某子串,如果不包含  location为NSNotFound
    if ([videoPath rangeOfString:@"http://"].location!=NSNotFound||[videoPath rangeOfString:@"https://"].location!=NSNotFound) {
        //远程的地址
        url = [NSURL URLWithString:videoPath];
    }else{
        //本地的播放路径
        url = [NSURL fileURLWithPath:videoPath];
    }
    if (!_playController) {
        //初始化控制器
        _playController = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
        //moviePlayer 视频播放器属性
        //movieSourceType 播放的视频资源的类型  MPMovieSourceTypeFile 普通的文件资源
        _playController.moviePlayer.movieSourceType =MPMovieSourceTypeFile;
        //通过模态化的方式呈现视频
        [self presentViewController:_playController animated:YES completion:^{
            [self stopAudioPlayer];//如果音频存在，停掉音频
        }];
        //准备播放
        [_playController.moviePlayer prepareToPlay];
        //播放
        [_playController.moviePlayer play];
        //还有后续的处理
        //NSNotificationCenter 通知中心,可以理解为应用程序的广播站,单例
        //addObserver 通过通知中心注册self成为某条广播的观察者，self就具有了收听这条广播的能力
        //一旦有其他对象通过通知中心发送MPMoviePlayerPlaybackDidFinishNotification,self就能收听到，继而触发后续的sel方法
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playVideoFinished) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
        //点击Done按钮，播放器会通过通知中心发送MPMoviePlayerPlaybackDidFinishNotification这条广播
        //[[NSNotificationCenter defaultCenter] postNotificationName:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    }
}
- (void)playVideoFinished{
    //通过通知中心，移除(注销)self对某条广播的观察
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    if (_playController) {
        [_playController.moviePlayer stop];
        _playController = nil;
    }
}



//通过音频资源路径，加载音频播放
- (void)loadAudioWithPath:(NSString *)audioPath{
    if (audioPath.length==0) {
        NSLog(@"没有音频资源");
        return;
    }
    //本地资源路径转化成url 用fileURLWithPath
    NSURL *url = [NSURL fileURLWithPath:audioPath];
    //上一首歌的播放对象存在，销毁掉
    if (_audioPlayer) {
        [_audioPlayer stop];
        _audioPlayer = nil;
    }
    //初始化播放对象，赋值播放的url
    _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    //设置代理
    _audioPlayer.delegate = self;
    //准备播放
    [_audioPlayer prepareToPlay];
    //播放
    [_audioPlayer play];
    //[_audioPlayer pause];//暂停
    //[_audioPlayer stop];//停止
}
//停掉音频播放器
- (void)stopAudioPlayer{
    if (_audioPlayer) {
        [_audioPlayer stop];
        _audioPlayer = nil;
    }
}



//根据不同的参数来加载不同的资源(相机、相册库)
//UIImagePickerController->封装了相册和相机资源
- (void)loadImagePickerWithType:(UIImagePickerControllerSourceType)type{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    //设置加载资源的参数
    picker.sourceType =type;
    //设置代理
    picker.delegate = self;
    //是否允许系统对相册资源进行编辑优化
    picker.allowsEditing =YES;
    //一般情况下，软件中用到相册库，通常使用模态化的方式呈现出来
    [self presentViewController:picker animated:YES completion:^{
        
    }];
}

//警告框提示不同的信息
- (void)showAlertViewWithMessage:(NSString *)msg{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alert show];
}


#pragma mark -AVAudioPlayerDelegate
//一首歌播放完成，调用此方法
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    NSLog(@"successed!");
}
//当软件有操作系统级别的功能(来电话、来短信)介入时,调用此方法，播放器会被自动中断
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{
    NSLog(@"begin interruption");
}
//播放器结束被打断，调用此方法
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags{
    if (player) {
        //继续播放
        [player play];
    }
}

#pragma mark - UIImagePickerControllerDelegate
//点击导航条上的cancel按钮的时候，触发此方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    NSLog(@"cancel!");
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}

//点击choose按钮时，触发此方法
//info 带有选中资源的信息
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    //先判断选中的资源类型:(图片或者视频)
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    //如果是图片资源
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        //获取到选中的图片
        UIImage *image  =[info objectForKey:UIImagePickerControllerEditedImage];
        self.view.backgroundColor = [UIColor colorWithPatternImage:image];
    }
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}







- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
